package demo1;

import java.util.Arrays;

public class MyStack {
    public int[] elem;
    public int usedSize;

    public MyStack() {
        elem = new int[5];
    }

    private boolean isFull() {
        if(usedSize == elem.length) {
            return true;
        }
        return false;
    }

    private void grow() {
        elem = Arrays.copyOf(elem,2*elem.length);
    }

    public void push(int val) {
        if(isFull()) {
            grow();
        }
        elem[usedSize++] = val;
    }

    private void checkPop() throws PopException{
        if(isEmpty()) {
            //抛异常
            throw new PopException("栈已空，无法删除！！！");
        }
    }

    public int pop() {
        try {
            checkPop();
            int ret = elem[usedSize-1];
            usedSize--;
            return ret;
        } catch (PopException e) {
            e.printStackTrace();
        }
        return -1;
    }

    //获取栈顶元素 但是不删除
    public int peek() {
        try {
            checkPop();
            return elem[usedSize-1];
        } catch (PopException e) {
            e.printStackTrace();
        }
        return -1;
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }
}
